package com.liming.file.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author liming
 * @date 2025/5/21
 */
@Slf4j
@RestController
@AllArgsConstructor
@Tag(name = "服务器本地文件操作-Service")
@RequestMapping("/service/local_file")
public class LocalFileController {

    @GetMapping("{fileName}")
    public void getFileByName(@PathVariable String fileName, HttpServletResponse response) {
        BufferedInputStream inputStream = FileUtil.getInputStream("download" + File.separator + fileName);
        response.setContentType("application/octet-stream");
        // 保持空格为 %20，更符合标准
        fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName);
        try (OutputStream outputStream = response.getOutputStream()) {
            IoUtil.copy(inputStream, outputStream);
            inputStream.close();
        } catch (Exception e) {
            log.error("上传文件失败", e);
        }
    }
}
